const DB = require('../../utils/db');

const { ipv6ToV4 } = require('../../utils/utlis');

const IP2Region = require('ip2region').default;
const query = new IP2Region();

module.exports = {
	add: async (ipv6, userId) => {
		// ipv6转ipv4
		let ip = ipv6ToV4(ipv6);

		const { country, province, city, isp } = query.search(ipv6);

		let [list] = await DB.query('select *  from t_visitor where ip=? and type=2', [ip]);

		// 如果当前ip有了，就不存了
		if (list.length) {
			if (list[0].userId) {
				await DB.query('update t_visitor set count=count+1 where ip=? and type=2', [ip]);
			} else {
				await DB.query('update t_visitor set count=count+1,userId=? where ip=? and type=2', [userId, ip]);
			}
		} else {
			await DB.query('insert into t_visitor (ip,ipv6,country,province,city,isp,type,count) values(?,?,?,?,?,?,2,1)', [ip, ipv6, country, province, city, isp]);
		}
	},
	list: async (pageNum, pageSize, keywords, type) => {
		let [allList] = await DB.query(`select *  from t_visitor where ip like '%${keywords}%' and type=${type}`);

		let arr = [(pageNum - 1) * pageSize, pageSize];
		let [list] = await DB.query(
			`
                  select v.*, date_format(v.createTime,'%Y-%m-%d %H:%i:%s') as createTime,u.username,u.email from 
                  t_visitor v left join t_user u on v.userId=u.id where v.ip like '%${keywords}%' and v.type=${type} order by v.createTime desc limit ?,?`,
			arr
		);
		return { data: list, total: allList.length };
	},
	del: async (ids) => {
		await DB.query('delete from t_visitor where id in (?)', [ids]);
		return true;
	}
};
